package com.seecen.HJM.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.HJM.mapper.AdminMapper;
import com.seecen.HJM.model.dto.AdminDto;
import com.seecen.HJM.model.entity.Admin;
import com.seecen.HJM.result.DataVo;
import com.seecen.HJM.service.AdminService;
import com.seecen.HJM.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //管理员登录
    @Override
    public DataVo login(AdminDto adminDto) {

        //根据用户名查找管理员信息
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminDto.getUsername());
        Admin admin = adminMapper.selectOne(queryWrapper);
        //验证用户是否存在
        if (admin == null) {
            return DataVo.error("用户名不存在");
        }
        //使用盐值验证密码
        if (!BCrypt.checkpw(adminDto.getPassword(), admin.getPassword())) {
            return DataVo.error("密码错误");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", admin.getAdminId());
        claims.put("username", admin.getUsername());
        claims.put("role", "admin");
        String token = JwtUtil.generateToken(claims);

        //令牌存入Redis
        stringRedisTemplate.opsForValue().set(
                "admin:token:" + token,
                admin.getAdminId().toString(),
                6,
                TimeUnit.HOURS
        );
        //返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("username", admin.getUsername());
        data.put("role", "admin");
        return DataVo.success("登陆成功", data);

    }

    //管理员注册
    @Override
    public DataVo register(AdminDto adminDto) {
        //检查用户是否存在
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminDto.getUsername());
        Admin existingadmin = adminMapper.selectOne(queryWrapper);
        if (existingadmin != null) {
            return DataVo.error("用户名已存在");
        }

        //使用盐值加密密码
        String encryptedPassword = BCrypt.hashpw(adminDto.getPassword(), BCrypt.gensalt());
        Admin admin = new Admin();
        admin.setUsername(adminDto.getUsername());
        admin.setPassword(encryptedPassword);
        //保存到数据库
        int rows = adminMapper.insert(admin);
        //返回注册结果
        if (rows > 0) {
            return DataVo.success("注册成功");
        } else {
            return DataVo.error("注册失败");
        }

    }

    @Override
    public DataVo loginOut(String token) {
        if (token == null) {
            return DataVo.error("令牌不能为空");
        }
        String redisKey = "admin:token:" + token;
        Boolean deleted = stringRedisTemplate.delete(redisKey);
        if (deleted != null && deleted) {
            return DataVo.success("退出登录成功");
        } else {
            return DataVo.error("退出登录失败,令牌不存在或已过期");
        }
    }
}
